package threadUtils.demo06;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 多个原子性操作放在一起，不一定会是原子性操作
 */
public class OriginLockExample {

    public static void main(String[] args) {

        final Bus bus = new Bus();
        for (int i = 0; i < 10; i++) {
            new BusThread(bus).start();
        }

    }

}

class BusThread extends Thread {

    private final Bus bus;

    public BusThread(Bus bus) {
        this.bus = bus;
    }

    @Override
    public void run() {
        int i = 100;
        while (i > 0) {
            i--;
            bus.setA();
            bus.setB();
            if (bus.getA() != bus.getB()) {
                System.out.printf("The a: %d not equals b: %d \n", bus.getA(), bus.getB());
            }
        }
    }
}

class Bus {

    private static final ReentrantLock lock = new ReentrantLock();
    private int a = 0;
    private int b = 0;

    public int getA() {
        lock.lock();
        try {
            return a;
        } finally {
            lock.unlock();
        }
    }

    public void setA() {
        lock.lock();
        try {
            a++;
        } finally {
            lock.unlock();
        }
    }

    public int getB() {
        lock.lock();
        try {
            return b;
        } finally {
            lock.unlock();
        }
    }

    public void setB() {
        lock.lock();
        try {
            b++;
        } finally {
            lock.unlock();
        }
    }
}